<script>
import pubsub from "pubsub-js";

export default {
  name: "MyItem",
  //声明要接收的任务对象
  props: ['todoObj'],
  data() {
    return {
      isdone: this.todoObj.done.toString(),
    }
  },
  watch: {
    todoObj: {
      deep: true,
      handler(value) {
        console.log(value)
        console.log(this.isdone)
      }
    }
  },
  methods: {
    handleCheck(id) {
      //发布订阅消息
      pubsub.publish('changeCheck', id)
    },
    deleteTodo(id) {
      //通过全局事件总线传递参数
      this.$bus.$emit('deleteTodo', id)
    },
    editItem(todoObj) {
      //判断是否有该属性
      // eslint-disable-next-line no-prototype-builtins
      if (!todoObj.propertyIsEnumerable('isEdit')) {
        //没有该属性就添加该属性
        console.log('添加了该属性')
        this.$set(todoObj, "isEdit", false)
      }
      //将该属性的值改为true,表示为正在编译状态
      todoObj.isEdit = true
      //自动获取焦点,这段代码没有作用,因为vue不是立马解析重新解析模板,他需要将这个函数都执行完之后才重新解析模板,因此在这个时机,input框还没出现

      //重新解析完模板,重新更新完DOM之后在调用这个方法
      this.$nextTick(() => {
        this.$refs.inputTitle.focus()
      })

    },
    //失去焦点时触发该事件
    blurHandler(todoObj, e) {
      //将可编辑的状态改成false
      todoObj.isEdit = false
      console.log(e.target.value)
      this.todoObj.title = e.target.value
    }
  }
}
</script>

<template>
  <!--  让标签动态有样式:checked='布尔表达式'-->
  <li :class="todoObj.done?'yes':'no'"><input type="checkbox" :checked="todoObj.done" @change="handleCheck(todoObj.id)">
    <input ref="inputTitle" id="Edit" v-if="todoObj.isEdit" type="text" v-bind:value="todoObj.title"
           @blur="blurHandler(todoObj,$event)">
    <span v-if="!todoObj.isEdit" v-text="todoObj.title"></span>
    <button @click="deleteTodo(todoObj.id)">删除</button>
    <button v-if="todoObj.isEdit!==true" @click="editItem(todoObj)">编辑</button>
  </li>


</template>

<style>
#Edit {
  margin-top: 2px;
  height: 80%;
  font-size: 18px;
  border: none;
}

.yes {
  border-radius: 10px;
  background-color: yellow;
}

.no {
  border-radius: 10px;
}
</style>